import CryptoJS from "crypto-js";
export default {
  namespaced: true,
  state: {
    user: undefined,
    loginInfo: undefined,
    permissions: null,
    routesConfig: null
  },
  getters: {
    user: state => {
      if (!state.user) {
        try {
          const user = localStorage.getItem(process.env.VUE_APP_USER_KEY)
          state.user = JSON.parse(user)
        } catch (e) {
          console.error(e)
        }
      }
      return state.user
    },
    permissions: state => {
      if (!state.permissions) {
        try {
          const permissions = localStorage.getItem(process.env.VUE_APP_PERMISSIONS_KEY)
          state.permissions = JSON.parse(permissions)
          state.permissions = state.permissions ? state.permissions : []
        } catch (e) {
          console.error(e.message)
        }
      }
      return state.permissions
    },
    routesConfig: state => {
      if (!state.routesConfig) {
        try {
          const routesConfig = localStorage.getItem(process.env.VUE_APP_ROUTES_KEY)
          state.routesConfig = JSON.parse(routesConfig)
          state.routesConfig = state.routesConfig ? state.routesConfig : []
        } catch (e) {
          console.error(e.message)
        }
      }
      return state.routesConfig
    },
    loginInfo: state => {
      if (!state.loginInfo) {
        try {
          const info = localStorage.getItem(process.env.VUE_APP_USER_LOGIN_KEY)
          if(info){
            const loginInfo = JSON.parse(CryptoJS.AES.decrypt(info, "login@sdf(kj1L.!~l").toString(CryptoJS.enc.Utf8))
            const time = new Date().getTime()
            if (time < loginInfo.expire) {
              state.loginInfo = loginInfo
            } else {
              state.loginInfo = undefined
              localStorage.removeItem(process.env.VUE_APP_USER_LOGIN_KEY)
            }
          }
        } catch (e) {
          console.error(e)
        }
      }
      return state.loginInfo
    }
  },
  mutations: {
    setUser (state, user) {
      state.user = user
      localStorage.setItem(process.env.VUE_APP_USER_KEY, JSON.stringify(user))
    },
    setPermissions(state, permissions) {
      state.permissions = permissions
      localStorage.setItem(process.env.VUE_APP_PERMISSIONS_KEY, JSON.stringify(permissions))
    },
    setRoutesConfig(state, routesConfig) {
      state.routesConfig = routesConfig
      localStorage.setItem(process.env.VUE_APP_ROUTES_KEY, JSON.stringify(routesConfig))
    },
    setLoginInfo (state, loginInfo) {
      state.loginInfo = loginInfo
      var cipherLoginInfo = CryptoJS.AES.encrypt(
        JSON.stringify(loginInfo),
        "login@sdf(kj1L.!~l"
      ).toString();
      localStorage.setItem(process.env.VUE_APP_USER_LOGIN_KEY, cipherLoginInfo)
    }
  }
}
